package day06.concurrent03;

/**
 * Lock 锁 - 解决线程同步安全问题
 */
public class Demo02 {
    static String name = "小明";
    static String gender = "男";
    static boolean isDBOK = false;
    static void saveToDB(String name,String gender){
        if(isDBOK){
            System.out.println("保存到数据库..");
        }else{
            //在非常耗时的操作执行之前，把锁释放掉，防止卡住其他线程很久很久
            //TODO:释放锁!!!!
            System.out.println("重连数据库..需耗时1小时..");
        }
    }

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    synchronized (Demo02.class){
                        saveToDB(name,gender);
                        System.out.println(name+"#"+gender);
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    synchronized (Demo02.class) {
                        if("小明".equals(name)){
                            name = "小花";
                            gender = "女";
                        }else{
                            name = "小明";
                            gender = "男";
                        }
                    }
                }
            }
        }).start();
    }
}
